import { _decorator, Component, Node, director, AudioSource, AudioClip } from 'cc';
import { Battle } from '../Battle';
import { EnEvent } from '../Common/const/EnEvent';
import { GameAPI } from '../Common/GameAPI';
import { Enum_AudioClip } from '../Enum';
import { ResourcesUtil } from '../ResourcesUtil';
const { ccclass, property } = _decorator;

@ccclass('GameOverPanel')
export class GameOverPanel extends Component {

    @property(Node) winDownloadNode: Node = null;
    @property(Node) failDownloadNode: Node = null;
    @property(Node) winNode: Node = null;
    @property(Node) failNode: Node = null;
    @property(Node) bgNode: Node = null;

    public _audioSound: AudioSource;
    public _willAudio: AudioClip = null;
    public _failAudio: AudioClip = null;
    private isWin: boolean = false;

    async onLoad(): Promise<void> {
        // 音频
        this._audioSound = this.node.getComponent(AudioSource);
        this._failAudio = await ResourcesUtil.loadAudioClip(Enum_AudioClip.lose);
        this._willAudio = await ResourcesUtil.loadAudioClip(Enum_AudioClip.motivation);
    }

    start() {
        this.winDownloadNode.on(Node.EventType.TOUCH_START, this.OnDownloadNode, this);
        this.failDownloadNode.on(Node.EventType.TOUCH_START, this.OnDownloadNode, this);
        GameAPI.RegGEvent(EnEvent.GameWinEvent, this.OnGameWinEvent.bind(this), this);
        GameAPI.RegGEvent(EnEvent.GameFailEvent, this.OnGameFailEvent.bind(this), this);
    }

    onDestroy() {
        GameAPI.OffAllCaller(this);
    }

    // 重新开始
    OnRepeatBattle() {
        // 恢复游戏逻辑
        director.resume();
        director.loadScene("Main");
    }

    OnDownloadNode() {

    }

    OnGameWinEvent() {
        this.isWin = true;
        this.OnInitPanel();
        if (this._audioSound && this._willAudio) {
            this._audioSound.playOneShot(this._willAudio);
        }
    }

    OnGameFailEvent() {
        this.isWin = false;
        this.OnInitPanel();
        if (this._audioSound && this._failAudio) {
            this._audioSound.playOneShot(this._failAudio);
        }
    }

    OnInitPanel() {
        if (Battle.startGame) {
            Battle.startGame = false;
            this.bgNode.active = true;
            if (this.isWin) {
                this.winNode.active = true;
            }
            else {
                this.failNode.active = true;
            }
        }
    }

}


